using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using hao_Dto.Product;
using hao_Model;
using hao_Reppsitory;
using hao_Common.AutoMapper.Services;
using hao_Common.Consul.Services;
using System.Text.Json;

namespace Product.Service
{
    /// <summary>
    /// 商品留言服务实现
    /// </summary>
    public class ProductCommentService : IProductCommentService
    {
        private readonly IProductCommentRepository _commentRepository;
        private readonly IProductCommentLikeRepository _likeRepository;
        private readonly IMapperService _mapperService;
        private readonly IServiceDiscovery _serviceDiscovery;
        private readonly HttpClient _httpClient;

        public ProductCommentService(
            IProductCommentRepository commentRepository,
            IProductCommentLikeRepository likeRepository,
            IMapperService mapperService,
            IServiceDiscovery serviceDiscovery,
            HttpClient httpClient)
        {
            _commentRepository = commentRepository;
            _likeRepository = likeRepository;
            _mapperService = mapperService;
            _serviceDiscovery = serviceDiscovery;
            _httpClient = httpClient;
        }

        /// <summary>
        /// 获取商品留言列表
        /// </summary>
        public async Task<ProductCommentListDto> GetCommentsAsync(ProductCommentQueryDto queryDto, Guid? currentUserId = null)
        {
            var (comments, total) = await _commentRepository.GetCommentsByProductIdAsync(
                queryDto.ProductId, queryDto.Page, queryDto.PageSize);

            var commentDtos = new List<ProductCommentDto>();

            foreach (var comment in comments)
            {
                var commentDto = await MapToCommentDto(comment, currentUserId);
                
                // 获取回复列表
                var replies = await _commentRepository.GetRepliesByParentIdAsync(comment.Id);
                foreach (var reply in replies)
                {
                    var replyDto = await MapToCommentDto(reply, currentUserId);
                    commentDto.Replies.Add(replyDto);
                }
                
                commentDtos.Add(commentDto);
            }

            return new ProductCommentListDto
            {
                Comments = commentDtos,
                Total = total,
                Page = queryDto.Page,
                PageSize = queryDto.PageSize,
                TotalPages = (int)Math.Ceiling((double)total / queryDto.PageSize)
            };
        }

        /// <summary>
        /// 创建留言
        /// </summary>
        public async Task<ProductCommentDto> CreateCommentAsync(CreateProductCommentDto createDto, Guid userId)
        {
            var comment = new ProductComment
            {
                Id = Guid.NewGuid(),
                ProductId = createDto.ProductId,
                UserId = userId,
                Content = createDto.Content,
                ParentId = createDto.ParentId,
                LikeCount = 0,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow,
                IsDeleted = false
            };

            await _commentRepository.AddAsync(comment);
            return await MapToCommentDto(comment, userId);
        }

        /// <summary>
        /// 点赞/取消点赞留言
        /// </summary>
        public async Task<bool> ToggleLikeAsync(Guid commentId, Guid userId)
        {
            var existingLike = await _likeRepository.GetLikeAsync(commentId, userId);
            
            if (existingLike != null)
            {
                // 取消点赞
                await _likeRepository.RemoveLikeAsync(commentId, userId);
                await _commentRepository.UpdateLikeCountAsync(commentId, -1);
                return false;
            }
            else
            {
                // 添加点赞
                await _likeRepository.AddLikeAsync(commentId, userId);
                await _commentRepository.UpdateLikeCountAsync(commentId, 1);
                return true;
            }
        }

        /// <summary>
        /// 删除留言
        /// </summary>
        public async Task<bool> DeleteCommentAsync(Guid commentId, Guid userId)
        {
            var comment = await _commentRepository.GetByIdAsync(commentId);
            if (comment == null || comment.UserId != userId)
            {
                return false;
            }

            comment.IsDeleted = true;
            await _commentRepository.UpdateAsync(comment);
            return true;
        }

        /// <summary>
        /// 获取留言详情
        /// </summary>
        public async Task<ProductCommentDto> GetCommentAsync(Guid commentId, Guid? currentUserId = null)
        {
            var comment = await _commentRepository.GetByIdAsync(commentId);
            if (comment == null || comment.IsDeleted)
            {
                return null;
            }

            return await MapToCommentDto(comment, currentUserId);
        }

        /// <summary>
        /// 映射留言实体到DTO
        /// </summary>
        private async Task<ProductCommentDto> MapToCommentDto(ProductComment comment, Guid? currentUserId)
        {
            var commentDto = _mapperService.Map<ProductCommentDto>(comment);
            
            // 获取用户信息
            commentDto.UserName = await GetUserNameAsync(comment.UserId);
            
            // 获取点赞状态
            if (currentUserId.HasValue)
            {
                commentDto.IsLiked = await _commentRepository.IsLikedByUserAsync(comment.Id, currentUserId.Value);
            }
            
            // 获取最新的点赞数量
            commentDto.LikeCount = await _commentRepository.GetLikeCountAsync(comment.Id);
            
            return commentDto;
        }

        /// <summary>
        /// 通过服务发现获取用户名
        /// </summary>
        private async Task<string> GetUserNameAsync(Guid userId)
        {
            try
            {
                var userServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-user-api");
                if (string.IsNullOrEmpty(userServiceUrl))
                {
                    return "匿名用户";
                }

                var response = await _httpClient.GetAsync($"{userServiceUrl}/api/user/{userId}");
                if (response.IsSuccessStatusCode)
                {
                    var userInfo = await response.Content.ReadAsStringAsync();
                    var userJson = JsonSerializer.Deserialize<JsonElement>(userInfo);
                    
                    // 尝试从不同的响应格式中获取用户名
                    if (userJson.TryGetProperty("data", out var dataElement))
                    {
                        if (dataElement.TryGetProperty("userName", out var userNameElement))
                        {
                            return userNameElement.GetString() ?? "匿名用户";
                        }
                    }
                    else if (userJson.TryGetProperty("userName", out var directUserNameElement))
                    {
                        return directUserNameElement.GetString() ?? "匿名用户";
                    }
                }
            }
            catch (Exception)
            {
                // 获取用户信息失败时返回默认值
            }
            
            return "匿名用户";
        }
    }
}